<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/20
 * Time: 14:28
 */

namespace app\adminapiv3\service;


class IpsConfig extends BaseService
{
    /**
     * @name 检查数据
     * @param $hostId
     * @param $data
     * @author wx
     * @date 2019/11/20 14:34
     */
    public function checkData($hostId, $data){
        //1. 验证主机的系统类型
        if($data['status'] == 1){
            $hostServer = new \app\common\service\Host();
            $hostInfo = $hostServer->info($hostId);
            $systemName = $hostInfo['os']; //1windows,2linux

            if(empty($data['type'])){
                $this->setError($this->CODE_FAIL, 'type不能为空');
                return false;
            }

            //type 1 => ips 2 => ids
            if($data['type'] == 1){
                if(empty($data['protect_ip'])){
                    $this->setError($this->CODE_FAIL, 'protect_ip不能为空');
                    return false;
                }
            }else{
                if(empty($data['device_ip'])){
                    $this->setError($this->CODE_FAIL, 'device_ip不能为空');
                    return false;
                }

                $data['lock'] = 0;
            }


            if(!is_numeric($data['black'] )){
                $this->setError($this->CODE_FAIL, 'black不能为空');
                return false;
            }

            //linux
            if($systemName == 2){
                if(!is_numeric($data['firewall'] )){
                    $this->setError($this->CODE_FAIL, 'firewall');
                    return false;
                }
            }
        }

        return true;
    }

    public function modify($hostId, $data)
    {
        //1. 验证数据
        $this->toDo('checkData', [$hostId, $data]);

        $server = new \app\common\service\IpsConfig();
        $info = $server->findData(['host_id' => $hostId]);

        if($info){
            //修改
            $server->modify(['host_id' => $hostId], $data);
        }else{
            //添加
            $data['host_id'] = $hostId;
            $data['ctime'] = time();
            $server->add($data);
        }

        return true;
    }

    public function findData($hostId)
    {
        $server = new \app\common\service\IpsConfig();
        $info = $server->findData(['host_id' => $hostId]);

        return $info;
    }
}